package org.jeecg.modules.rental.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.plugins.pagination.PageDTO;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.jeecg.common.api.vo.Result;
import org.jeecg.common.aspect.annotation.AutoLog;
import org.jeecg.common.aspect.annotation.PermissionData;
import org.jeecg.common.system.base.controller.JeecgController;
import org.jeecg.common.system.query.QueryGenerator;
import org.jeecg.common.util.CommonUtils;
import org.jeecg.modules.rental.entity.RentalEBike;
import org.jeecg.modules.rental.entity.RentalFaultHandle;
import org.jeecg.modules.rental.entity.RentalRepairType;
import org.jeecg.modules.rental.enums.FaultObjTypeEnums;
import org.jeecg.modules.rental.service.IRentalEBikeService;
import org.jeecg.modules.rental.service.IRentalFaultHandleService;
import org.jeecg.modules.rental.service.IRentalRepairTypeService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.format.annotation.DateTimeFormat;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartRequest;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.time.LocalDateTime;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * @Description: 故障处理
 * @Author: sean
 * @Date: 2024-07-23
 * @Version: V1.0
 */
@Api(tags = "故障处理")
@RestController
@RequestMapping("/rental/fault-handle")
@Slf4j
public class RentalFaultHandleController extends JeecgController<RentalFaultHandle, IRentalFaultHandleService> {

	@Autowired
    private IRentalFaultHandleService rentalFaultHandleService;

    @Autowired
    private IRentalEBikeService rentalEBikeService;

    @Autowired
    private IRentalRepairTypeService rentalRepairTypeService;


    @Value(value="${jeecg.uploadType}")
    private String uploadAvatarType;

    @Value(value = "${jeecg.path.upload}")
    private String uploadAvatarpath;

    /**
     * 分页列表查询
     *
     * @param rentalFaultHandle
     * @param pageNo
     * @param pageSize
     * @return
     */
    //@AutoLog(value = "故障处理-分页列表查询")
    @ApiOperation(value = "故障处理-分页列表查询", notes = "故障处理-分页列表查询")
    @GetMapping(value = "/list")
    @PermissionData(pageComponent="rental/keep/handlelist")
    public Result<IPage<RentalFaultHandle>> queryPageList(RentalFaultHandle rentalFaultHandle,  @RequestParam(name = "pageNo", defaultValue = "1") Integer pageNo,
                                                          @RequestParam(name = "pageSize", defaultValue = "10") Integer pageSize,
                                                          HttpServletRequest request) {
        QueryWrapper<RentalFaultHandle> queryWrapper = QueryGenerator.initQueryWrapper(rentalFaultHandle, request.getParameterMap());
        Page<RentalFaultHandle> page = new Page<>(pageNo, pageSize);
        IPage<RentalFaultHandle> pageList = rentalFaultHandleService.page(page, queryWrapper);
        return Result.OK(pageList);
    }

    /**
     * 添加
     *
     * @param rentalFaultHandle
     * @return
     */
    @AutoLog(value = "故障处理-添加")
    @ApiOperation(value = "故障处理-添加", notes = "故障处理-添加")
    @PostMapping(value = "/add")
    public Result<String> add(@RequestBody RentalFaultHandle rentalFaultHandle) {
        rentalFaultHandleService.save(rentalFaultHandle);
        return Result.OK("common.add.success");
    }

    @AutoLog(value = "故障处理-申报")
    @ApiOperation(value = "故障处理-申报", notes = "故障处理-申报")
    @PostMapping(value = "/report")
    public Result<String> report(@RequestBody RentalFaultHandle rentalFaultHandle) {
        rentalFaultHandleService.report(rentalFaultHandle);
        return Result.OK("common.add.success");
    }

    @AutoLog(value = "小程序车辆故障处理报修")
    @ApiOperation(value = "小程序车辆故障处理报修", notes = "小程序车辆故障处理报修")
    @PostMapping(value = "/wx-vehicle-report")
    public Result<String> wxVehicleReport(@RequestParam("file") MultipartFile file, RentalFaultHandle rentalFaultHandle) {
        rentalFaultHandleService.wxVehicleReport(rentalFaultHandle, file);
        return Result.OK("上报故障成功！");
    }

    @AutoLog(value = "指定故障处理人")
    @ApiOperation(value = "指定故障处理人", notes = "指定故障处理人")
    @PostMapping(value = "/assign-handler")
    public Result<String> assignHandler(@RequestBody RentalFaultHandle rentalFaultHandle) {
        rentalFaultHandleService.assignHandler(rentalFaultHandle);
        return Result.OK("指定故障处理人成功！");
    }

    @AutoLog(value = "故障处理")
    @ApiOperation(value = "故障处理", notes = "故障处理")
    @PostMapping(value = "/handle")
    public Result<String> faultHandle(MultipartRequest files, RentalFaultHandle rentalFaultHandle) {
        rentalFaultHandleService.faultHandle(rentalFaultHandle, files);
        return Result.OK("上报故障成功！");
    }

    /**
     * 编辑
     *
     * @param rentalFaultHandle
     * @return
     */
    @AutoLog(value = "故障处理-编辑")
    @ApiOperation(value = "故障处理-编辑", notes = "故障处理-编辑")
    @RequestMapping(value = "/edit", method = {RequestMethod.PUT, RequestMethod.POST})
    public Result<String> edit(@RequestBody RentalFaultHandle rentalFaultHandle) {
        rentalFaultHandleService.updateById(rentalFaultHandle);
        return Result.OK("common.edit.success");
    }

    /**
     * 通过id删除
     *
     * @param id
     * @return
     */
    @AutoLog(value = "故障处理-通过id删除")
    @ApiOperation(value = "故障处理-通过id删除", notes = "故障处理-通过id删除")
    @DeleteMapping(value = "/delete")
    public Result<String> delete(@RequestParam(name = "id", required = true) String id) {
        rentalFaultHandleService.removeById(id);
        return Result.OK("common.delete.success");
    }

    /**
     * 批量删除
     *
     * @param ids
     * @return
     */
    @AutoLog(value = "故障处理-批量删除")
    @ApiOperation(value = "故障处理-批量删除", notes = "故障处理-批量删除")
    @DeleteMapping(value = "/deleteBatch")
    public Result<String> deleteBatch(@RequestParam(name = "ids", required = true) String ids) {
        this.rentalFaultHandleService.removeByIds(Arrays.asList(ids.split(",")));
        return Result.OK("common.delete.batch.success");
    }

    /**
     * 通过id查询
     *
     * @param id
     * @return
     */
    //@AutoLog(value = "故障处理-通过id查询")
    @ApiOperation(value = "故障处理-通过id查询", notes = "故障处理-通过id查询")
    @GetMapping(value = "/queryById")
    public Result<RentalFaultHandle> queryById(@RequestParam(name = "id", required = true) String id) {
        RentalFaultHandle rentalFaultHandle = rentalFaultHandleService.queryById(id);
        if (rentalFaultHandle == null) {
            return Result.error("common.query.not.found", null);
        }
        return Result.OK(rentalFaultHandle);
    }

    /**
     * 导出excel
     *
     * @param request
     * @param rentalFaultHandle
     */
    @RequestMapping(value = "/exportXls")
    public ModelAndView exportXls(HttpServletRequest request, RentalFaultHandle rentalFaultHandle) {
        return super.exportXls(request, rentalFaultHandle, RentalFaultHandle.class, "故障处理");
    }

    /**
     * 通过excel导入数据
     *
     * @param request
     * @param response
     * @return
     */
    @RequestMapping(value = "/importExcel", method = RequestMethod.POST)
    public Result<?> importExcel(HttpServletRequest request, HttpServletResponse response) {
        return super.importExcel(request, response, RentalFaultHandle.class);
    }

    @AutoLog(value = "故障处理-报修")
    @ApiOperation(value = "故障处理-报修", notes = "故障处理-报修")
    @PostMapping(value = "/reportFault")
    public Result<String> reportFault(
            MultipartRequest files, RentalFaultHandle rentalFaultHandle
    ) {
        try {
            // 创建故障处理实体
            RentalFaultHandle faultHandle = new RentalFaultHandle();
            faultHandle.setObjType("1");
            faultHandle.setFaultDesc(rentalFaultHandle.getFaultDesc()); // 设置故障描述
            faultHandle.setFaultStatus("0"); // 设置默认故障状态为“待处理”
            faultHandle.setFaultCode(rentalFaultHandle.getFaultType());// 设置故障类型
            faultHandle.setReportedDate(LocalDateTime.now()); // 设置当前时间为报告时间
            faultHandle.setObjCode(rentalFaultHandle.getCarCode());

            QueryWrapper<RentalEBike> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("car_code",rentalFaultHandle.getCarCode() ); // 条件：car_code = carCode
            // 查询记录
            RentalEBike ebike = rentalEBikeService.getOne(queryWrapper);
            faultHandle.setObjId(ebike.getId());

            // 保存图片
            // 处理文件上传
            StringBuilder imagePaths = new StringBuilder();
            if (files != null && files.getMultiFileMap() != null) {
                files.getMultiFileMap().forEach((key, multipartFiles) -> {
                    for (MultipartFile file : multipartFiles) {
                        // 上传图片并获取保存路径
                        try {
                            String filePath = CommonUtils.uploadnew(file, uploadAvatarpath, "fault_images", uploadAvatarType);

                            filePath="http://192.168.1.24:9999/sys/common/static/"+filePath;
                            if (filePath != null) {
                                imagePaths.append(filePath).append(","); // 多张图片用逗号分隔
                            }
                        } catch (Exception e) {
                            log.error("文件上传失败：" + file.getOriginalFilename(), e);
                        }
                    }
                });

                if (imagePaths.length() > 0) {
                    imagePaths.deleteCharAt(imagePaths.length() - 1); // 移除最后一个逗号
                }
            }
            faultHandle.setFaultAttach(imagePaths.toString()); // 设置故障图片路径

            // 保存数据到数据库
            rentalFaultHandleService.save(faultHandle);

            return Result.OK("报修成功！");
        } catch (Exception e) {
            log.error("故障报修失败", e);
            return Result.error("报修失败：" + e.getMessage());
        }
    }


    @AutoLog(value = "故障处理-获取故障类型列表")
    @ApiOperation(value = "故障处理-获取故障类型列表", notes = "故障处理-获取故障类型列表")
    @GetMapping(value = "/faultTypeList")
    public Result<List<Map<String, String>>> getFaultTypeList() {
        try {
            // 构建返回结果
            List<Map<String, String>> faultTypeList = Arrays.stream(FaultObjTypeEnums.values())
                    .map(enumItem -> {
                        Map<String, String> map = new HashMap<>();
                        map.put("text", enumItem.getLabel()); // 故障名称
                        map.put("value", enumItem.getValue()); // 故障编号
                        return map;
                    }).collect(Collectors.toList());

            return Result.OK(faultTypeList);

        } catch (Exception e) {
            log.error("获取故障类型列表失败", e);
            return Result.error("获取故障类型列表失败：" + e.getMessage());
        }
    }

    @AutoLog(value = "故障处理-报修记录列表")
    @ApiOperation(value = "故障处理-报修记录列表", notes = "故障处理-报修记录列表")
    @GetMapping(value = "/faultRecordList")
    public Result<Page<Map<String, Object>>> getFaultRecordList(
            @RequestParam(value = "carCode", required = false) String carCode,
            @RequestParam(value = "startDate", required = false) @DateTimeFormat(pattern = "yyyy-MM-dd") String startDate,
            @RequestParam(value = "endDate", required = false) @DateTimeFormat(pattern = "yyyy-MM-dd") String endDate,
            @RequestParam(value = "faultType", required = false) String faultType,
            @RequestParam(value = "status", required = false) String status,
            @RequestParam(name = "pageNo", defaultValue = "1") Integer pageNo,
            @RequestParam(name = "pageSize", defaultValue = "10") Integer pageSize
    ) {
        try {
            // 构建查询条件
            QueryWrapper<RentalFaultHandle> queryWrapper = new QueryWrapper<>();
            if (carCode != null && !carCode.isEmpty()) {
                queryWrapper.eq("obj_code", carCode); // 根据车辆编号查询
            }
            if (startDate != null && !startDate.isEmpty()) {
                queryWrapper.ge("reported_date", startDate); // 开始时间筛选
            }
            if (endDate != null && !endDate.isEmpty()) {
                queryWrapper.le("reported_date", endDate); // 结束时间筛选
            }
            if (faultType != null && !faultType.isEmpty()) {
                queryWrapper.eq("obj_type", faultType); // 故障类型筛选
            }
            if (status != null && !status.isEmpty()) {
                queryWrapper.eq("fault_status", status); // 故障状态筛选
            }
            queryWrapper.orderByDesc("reported_date"); // 按报告时间倒序排序

            // 分页查询

            Page<RentalFaultHandle> page = new Page<>(pageNo, pageSize);
            IPage<RentalFaultHandle> pageList = rentalFaultHandleService.page(page, queryWrapper);
            Map<String, String> repairTypeMap = rentalRepairTypeService.list().stream()
                    .collect(Collectors.toMap(RentalRepairType::getCode, RentalRepairType::getName));
            // 构建返回结果
            List<Map<String, Object>> resultList = pageList.getRecords().stream().map(record -> {
                Map<String, Object> map = new HashMap<>();
                map.put("carCode", record.getObjCode()); // 车辆编号
                map.put("date", record.getReportedDate()); // 报修时间
                map.put("faultType", repairTypeMap.getOrDefault(record.getFaultCode(), "未知类型")); // 故障类型名称
                map.put("faultDesc", record.getFaultDesc()); // 故障描述
                map.put("status", record.getFaultStatus()); // 故障状态
                return map;
            }).collect(Collectors.toList());

            Page<Map<String, Object>> pageList2 = new Page<>(pageList.getCurrent(), pageList.getSize(), pageList.getTotal());
            pageList2.setRecords(resultList);

            // 返回结果
            return Result.OK(pageList2);

        } catch (Exception e) {
            log.error("获取报修记录列表失败", e);
            return Result.error("获取报修记录列表失败：" + e.getMessage());
        }
    }

}
